package com.wans.guli.auth.controller;

import cn.hutool.http.useragent.UserAgentUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wans.guli.auth.feign.IntegrationFeignClient;
import com.wans.guli.auth.feign.MemberFeignClient;
import com.wans.guli.auth.vo.oauth.MemberVO;
import com.wans.guli.auth.vo.oauth.OAuthAccessParam;
import com.wans.guli.auth.vo.oauth.OAuthAccessVO;
import com.wans.guli.common.utils.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@Slf4j
public class GiteeOAuth2Controller {

    @Autowired
    private IntegrationFeignClient integrationFeignClient;
    @Autowired
    private MemberFeignClient memberFeignClient;
    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/login/oauth2")
    @SneakyThrows
    public String giteeLogin(@RequestParam("code") String code, HttpSession session) {

        OAuthAccessParam param = new OAuthAccessParam();
        param.setGrant_type("authorization_code");
        param.setCode(code);
        param.setClient_id("40e984f54849bf116487b3eea39c889dbf82d893eeded6dca4d2b2e6d4edaffb");
        param.setClient_secret("e3b1484e21b41b038687b74f4e815af3a43f1f265fdc464a3b4398b478a8d237");
        param.setRedirect_uri("http://auth.gulimall.com/login/oauth2");

        R result = integrationFeignClient.getAccessToken(param);

        OAuthAccessVO data = null;
        if (result.getCode() != 0) {
            // 获取失败
            log.error("远程换取OAuthAccess失败");
            return "login";
        }


        // 获取成功
        data = result.getData(OAuthAccessVO.class);
        // 获取用户信息
        R userInfoR = memberFeignClient.getUserInfo(data.getAccess_token());
        if (userInfoR.getCode() != 0) {
            // 获取用户信息失败
            log.error("远程获取用户社交信息失败");
            return "login";
        }
        MemberVO userInfo = userInfoR.getData(MemberVO.class);
        // 隐藏部分数据
        userInfo.setGiteeId(null);
        userInfo.setLevelId(null);
        userInfo.setStatus(null);
        userInfo.setCreateTime(null);
        userInfo.setGrowth(null);
        userInfo.setIntegration(null);

        String stringUserInfo = objectMapper.writeValueAsString(userInfo);
        session.setAttribute("loginMember", stringUserInfo);

        return "redirect:http://gulimall.com/";

    }

}
